package icu.twtool.entity

import java.io.PrintStream
import java.nio.file.Path
import kotlin.io.path.readText

/**
 * 练习，做题的结果
 * @author Wen
 * @since 2022-11-01
 */
class Practice(
    val name: String
) {

    /**
     * 练习结果
     */
    private val answers = mutableListOf<Int>()

    /**
     * 答案数
     */
    val size get() = answers.size

    /**
     * 将答案添加到答案集
     */
    fun add(answer: Int) {
        answers.add(answer)
    }

    /**
     * 获取对应索引位置的答案
     */
    operator fun get(index: Int): Int {
        return answers[index]
    }

    @Throws(IllegalStateException::class)
    fun judge(exercise: Exercise): JudgeResult {
        if (exercise.size != size) error("习题算式数和答案数不一致")
        var right = 0
        for (i in 0 until size) {
            if (exercise.get(i).answer() == answers[i]) right++
        }
        return JudgeResult(name, size, right)
    }

    /**
     * 输出答案
     *
     * @param column 习题每行的算式数
     * @param out 输出字符流，默认输出到控制台
     */
    fun write(column: Int = 5, out: PrintStream = System.out) {
        answers.forEachIndexed { index, answer ->
            if (index % column == 0) {
                if (index > 0) out.println()
            }
            out.print("$answer, ")
        }
        out.println()
    }

    companion object {

        /**
         * 答案的格式为正负数字加英文逗号，-1为没有做出来
         */
        private val ANSWER_REGEX = Regex("(-?\\d+)\\s*,")

        /**
         * 读取结果
         */
        fun readFile(path: Path): Practice {
            val result = Practice(path.fileName.toString())
            ANSWER_REGEX.findAll(path.readText()).forEach {
                result.add(it.groupValues[1].toInt())
            }
            return result
        }
    }


}